package com.dzpk.gameserver.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AsynThreadControler {

    public static final Logger logger = LoggerFactory.getLogger(AsynThreadControler.class);

    private int threadCount;

    private int timeOut;

    private String descName;

    private ExecutorService service;

    public void setDescName(String descName) {
        this.descName = descName;
    }

    public String getName() {
        return descName;
    }

    public int getThreadCount() {
        return threadCount;
    }

    public void setThreadCount(int threadCount) {
        this.threadCount = threadCount;
    }

    public void execute(Runnable thread) {
        service.execute(thread);
    }

    public void init() {
        service = Executors.newFixedThreadPool(threadCount, new AsynThreadFactory(descName));
    }

    public void destroy() {
        if (service != null) {
            service.shutdown();
            try {
                service.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                logger.error("AsynThreadControler destory error", e);
            }
        }
    }

    public int getTimeOut() {
        return timeOut;
    }

    public void setTimeOut(int timeOut) {
        this.timeOut = timeOut;
    }

    private static class AsynThreadFactory implements ThreadFactory {

        AtomicInteger number = new AtomicInteger(1);

        private String threadName;

        private AsynThreadFactory(String name) {
            super();
            this.threadName = name;
        }

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, threadName + "-" + number.getAndIncrement());
        }
    }

}
